package com.iteaj.iot.client.codec;

import com.iteaj.iot.SocketMessage;
import com.iteaj.iot.client.ClientComponent;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.codec.adapter.FixedLengthFrameDecoderAdapter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;

public class FixedLengthFrameClient extends TcpSocketClient {

    private int frameLength;

    public FixedLengthFrameClient(ClientComponent clientComponent, ClientConnectProperties config, int frameLength) {
        super(clientComponent, config);
        this.frameLength = frameLength;
    }

    @Override
    protected ChannelInboundHandler createProtocolDecoder() {
        return new FixedLengthFrameDecoderAdapter(frameLength) {

            @Override
            public Class<? extends SocketMessage> getMessageClass() {
                return FixedLengthFrameClient.this.getClientComponent().getMessageClass();
            }

            @Override
            public SocketMessage proxy(ChannelHandlerContext ctx, ByteBuf decode) throws Exception {
                return FixedLengthFrameClient.this.getClientComponent().proxy(ctx, decode);
            }

            @Override
            public SocketMessage doDecode(ChannelHandlerContext ctx, ByteBuf decode) {
                return FixedLengthFrameClient.this.getClientComponent().doDecode(ctx, decode);
            }

            @Override
            public SocketMessage createMessage(byte[] message) {
                return FixedLengthFrameClient.this.getClientComponent().createMessage(message);
            }
        };
    }

    public int getFrameLength() {
        return frameLength;
    }

    public void setFrameLength(int frameLength) {
        this.frameLength = frameLength;
    }
}
